package com.dyh.quickdemozwei.util;

import com.google.common.collect.Sets;
import org.springframework.util.StringUtils;

import java.lang.reflect.Method;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author: yhdong
 * @Date: 2021/8/31 15:46
 */
public class ReflectUtil {
    public static final Set<String> getterMethodPrefixs = Sets.newHashSet(
            "is","get"
    );

    public static final Set<String> setterMethodPrefixs = Sets.newHashSet(
            "set"
    );

    //public static final Set<String> needTrim = new HashSet<>();

    public static final  Set<String>  getterMethodIgnorePrefixs = Sets.newHashSet(
            "getClass"
    );

//    static {
//        needTrim.addAll(getterMethodIgnorePrefixs);
//        needTrim.addAll(setterMethodPrefixs);
//    }


    public static    Map<String,Method>findGetterMethods(Class cls){
        Map<String,Method> name2method = new HashMap<>();
        for (Method method : cls.getMethods()) {
            String methodName = method.getName();
            boolean match = false;
            for (String prefix:getterMethodPrefixs){
                if (methodName.startsWith(prefix)){
                    match = true;
                    break;
                }
            }
            for (String prefix:getterMethodIgnorePrefixs){
                if (methodName.startsWith(prefix)){
                    match = false;
                    break;
                }
            }
            if (match){
                String pureName = StringUtils.uncapitalize(methodName.replaceAll("is|get|set",""));
                name2method.put(pureName,method);
            }

        }

        return name2method;
    }

    public static    Map<String,Method>findSetterMethods(Class cls){
        Map<String,Method> name2method = new HashMap<>();
        for (Method method : cls.getMethods()) {
            String methodName = method.getName();
            boolean match = false;
            for (String prefix:setterMethodPrefixs){
                if (methodName.startsWith(prefix)){
                    match = true;
                    break;
                }
            }
            if (match){
                String pureName = StringUtils.uncapitalize(methodName.replaceAll("is|get|set",""));
                name2method.put(pureName,method);
            }

        }

        return name2method;
    }
}
